/* Server IO Thread
 * sends and recieves data from a socket that a client is connected to
 * This data should be commands encoded to JSON
 * They are decoded to objects and given to the player
 */
package sbcc.edu.blackjack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import sbcc.edu.blackjack.command.Command;
import sbcc.edu.blackjack.command.CommandQueue;

import com.google.gson.Gson;

public class ServerIOThread extends Thread {
    private Socket socket = null;
    private CommandQueue playerQueue = null;
    private Gson gson;
	private boolean playing;

    public ServerIOThread(Socket socket, CommandQueue cq) {
    	super("Server IO Thread");
    	this.socket = socket;
    	this.playerQueue = cq;
    	gson = new Gson();
    }
    
    public void stopThread(){
    	playing = false;
    }

    public void run() {
	    try {
		    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
		    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		    playing = true;
		    String inputLine, outputLine = null;
		    System.out.println("ServerIO Thread started");
		    out.println("hello Player");
		    
		    while (playing) {	//FIXME should continue waiting to read forever
		    	inputLine = in.readLine();
		    	//decode inputLine to an object
		    	Command received = gson.fromJson(inputLine, Command.class);
		    	//add to command queue
		    	playerQueue.add(received);		//picked up through player object by busy-waiting table operator
		    	
		    	Command toSend;
		    	//if command queue has commands waiting
		    	if ((toSend = playerQueue.poll()) != null){
		    		outputLine = gson.toJson(toSend);
		    		out.print(outputLine);
		    	}
		    }
		    out.close();
		    in.close();
		    socket.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
    }
}
